using System;
using System.ComponentModel;
using System.Configuration;
using System.Reactive;
using System.Reactive.Linq;

using VSTalk.Engine.Core.EntitySession;
using VSTalk.Engine.ViewModel.ContactList.ClientResources;
using VSTalk.Model;
using VSTalk.Tools;

namespace VSTalk.Engine.ViewModel.ContactList.Filter
{
    public class HideOfflineContactFilter : IResourceFilter, IObservableResource
    {
        public IObservable<Unit> Trigger
        {
            get
            {
                return Observable.FromEventPattern<SettingsSavingEventHandler, CancelEventArgs>(
                        addHandler => Properties.Settings.Default.SettingsSaving += addHandler,
                        removeHandler => Properties.Settings.Default.SettingsSaving -= removeHandler)
                        .SelectMany(Observable.Return(Unit.Default));
            }
        }

        private static ISessionModel SessionModel
        {
            get { return AppServices.Get<ISessionModel>(); }
        }

        private bool ShowOffline
        {
            get { return Properties.Settings.Default.ShowOfflineContacts; }
        }

        public FilterResult Apply(IClientResource clientResource)
        {
            var interlocutorNode = clientResource as InterlocutorResourceViewModel;
            if (interlocutorNode == null)
            {
                return FilterResult.Accepted;
            }
            if (!ShowOffline)
            {
                var context = SessionModel.GetInterlocutorContext(interlocutorNode.Interlocutor);
                if (context.State == ContactState.Offline)
                {
                    return FilterResult.Rejected;
                }
            }
            return FilterResult.Accepted;
        }
    }
}